<template>
    <div class="maind" style="padding-top:40px ;height: calc(100% - 5px);">
        <main>
            <el-header>

                <el-button class="add" size="small" @click="addForms()">新增</el-button>
            </el-header>
            <!-- 数据渲染的列表 -->
            <el-table style="height:calc(100% - 85px);" :data="assignmentList" border row-key="menuId" :row-style="{ height: '30px' }"
                size="small"
                :cell-style="{ padding: '0px' }">


                <el-table-column prop="name" label="名称" width="180"></el-table-column>  
                <el-table-column prop="perms" label="上级菜单" width="180"></el-table-column>  
                <el-table-column prop="icon" label="图标">
                    <template slot-scope="scope">
                        <i :class="scope.row.icon"></i>
                    </template>
                </el-table-column>  
                <el-table-column prop="type" label="类型">
                    <template slot-scope="scope">
                        <el-tag type="danger" v-show="scope.row.type == 0" size="mini">目录</el-tag>
                        <el-tag type="warning" v-show="scope.row.type == 1" size="mini">菜单</el-tag>
                    </template>
                </el-table-column>  
                <el-table-column prop="orderNum" label="排序号"></el-table-column>  
                <el-table-column prop="url" label="菜单URL" width="180"></el-table-column>  
                <el-table-column prop="perms" label="授权标识"></el-table-column>  
                
                <el-table-column label="操作" fixed="right" width="120">
                    <template slot-scope="scope">
                        <el-button style="color: #17b3a3; " size="mini" type="text"
                            @click="handleEdit(scope.row)">修改</el-button>
                        <el-button style="color: #17b3a3; " size="mini" type="text"
                            @click="handleDelete(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>



            <!-- 新增或者编辑 -->
            <el-dialog :title="id ? '修改' : '新增'" :visible.sync="dialogFormVisible">
                
                
                <el-form :model=" Type == 0 ?cataloguement:Type == 1?addassignment:buttons" :rules="rules" ref="addassignment" label-width="100px" size="mini"
                    class="demo-ruleForm">
                    <el-row :gutter="20">
                        <el-col :span="24">
                            <el-form-item label="类型">
                                <el-radio-group v-model="Type">
                                <el-radio :label="0">目录</el-radio>
                                <el-radio :label="1">菜单</el-radio>
                                <el-radio :label="2">按钮</el-radio>
                            </el-radio-group>
                            </el-form-item>
                        </el-col>

                        <!-- 菜单 -->
                        <aside v-if="Type == 1">
                        <el-col :span="24">
                            <el-form-item label="菜单名称">
                                <el-input v-model="addassignment.name" placeholder="菜单名称"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="菜单路由">
                                <Treeselect v-model="addassignment.parentId" :options="options" :placeholder="'请选择'" :normalizer="tenantIdnormalizer" :multiple="false" :value-consists-of="valueConsistsOf"/>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="菜单URL">
                                <el-input v-model="addassignment.url" placeholder="菜单URL"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="授权标识">
                                <el-input v-model="addassignment.perms" placeholder="授权标识"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="排序号">
                                <el-input-number v-model="addassignment.orderNum" :min="1" :max="100" @change="Age" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="菜单图标">
                                <el-input v-model="addassignment.icon" placeholder="菜单图标"></el-input>
                            </el-form-item>
                        </el-col>
                    </aside>
                        <!-- 目录 -->
                         <aside v-if="Type == 0">
                            <el-col :span="24">
                                <el-form-item label="目录名称">
                                    <el-input v-model="cataloguement.name" placeholder="菜单名称"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="24">
                            <el-form-item label="上级菜单">
                                <Treeselect v-model="cataloguement.parentId" :options="options" :placeholder="'请选择'" :normalizer="tenantIdnormalizer" :multiple="false" :value-consists-of="valueConsistsOf"/>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="排序号">
                                <el-input-number v-model="cataloguement.orderNum" :min="1" :max="100" @change="width" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="菜单图标">
                                <el-input v-model="cataloguement.icon" placeholder="菜单图标"></el-input>
                            </el-form-item>
                        </el-col>
                         </aside>
                         <!-- 按钮 -->
                         <aside v-if="Type == 2">
                            <el-col :span="24">
                                <el-form-item label="按钮名称">
                                    <el-input v-model="buttons.name" placeholder="菜单名称"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="24">
                            <el-form-item label="上级菜单">
                                <Treeselect v-model="buttons.parentId" :options="options" :placeholder="'请选择'" :normalizer="tenantIdnormalizer" :multiple="false" :value-consists-of="valueConsistsOf"/>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="授权标识">
                                <el-input v-model="buttons.perms" placeholder="授权标识"></el-input>
                            </el-form-item>
                        </el-col>
                         </aside>    
                    </el-row>
                    <el-form-item v-if="Type == 0">
                        <el-button v-if="id" type="primary" @click="editFormA()">修改</el-button>
                        <el-button v-else type="primary" @click="addFormA()">添加</el-button>
                        <el-button @click="resetForm()">取消</el-button>
                    </el-form-item>
                    <el-form-item v-if="Type == 1">
                        <el-button v-if="id" type="success" @click="editForm()">修改</el-button>
                        <el-button v-else type="success" @click="addForm()">添加</el-button>
                        <el-button @click="resetForm()">取消</el-button>
                    </el-form-item>
                    <el-form-item v-if="Type == 2">
                        <el-button v-if="id" type="warning" @click="editFormB()">修改</el-button>
                        <el-button v-else type="warning" @click="addFormB()">添加</el-button>
                        <el-button @click="resetForm()">取消</el-button>
                    </el-form-item>
                </el-form>
            </el-dialog>




            <pagination :page="queryInfo.page" :componentTotal="total" @changeRows="setRows" @changePage="setPage" style="display: none;">
            </pagination>


        </main>
    </div>
</template>

<script>
import Pagination from "../Pagination.vue";
export default {
    data() {
        return {
            id: '',
            dialogFormVisible: false,
            esdisabled: true,
            readonly: false,
            total: 0,
            queryInfo: {
                t: '',
                page: 1,
                limit: 10,
                username: '',
            },
            //信息添加时候弹出的表单数据
            RRRROU: {
                rouqi: '',//容器名称
                jia: '',//冻存架
                he: '',//盒子
            },




             Type: 2,


            

            //动态获取到的数据
            assignmentList: [],
            //接口需要上传的数据-------------------------------【菜单】
            addassignment: {
                "t": 1729667138714,
                "type": '1',//类型
                "name": "AAD测试测试",//菜单名称
                "parentId": 162,//上级菜单的ID
                "url": "菜单路由",//菜单路由
                "perms": "useruserUSER",//授权标识
                "orderNum": 20,//排序号
                "icon": "xiangqufill"//ICO
            },
            //----------------------------------------------【目录】
            cataloguement:{
                "t": 1729668942169,
                "type": 0,
                "name": "大魔测试",
                "parentId": 0,
                "url": 0,
                "perms": 0,
                "orderNum": 50,
                "icon": "admin"
            },
            //----------------------------------------------【按钮】
            buttons:{
                "t": 1729670921585,
                "type": 2,
                "name": "DA大魔测试",
                "parentId": 210,
                "url": 0,
                "perms": "userUSRR",
                "orderNum": 0,
                "icon": ""
            },























            
          


            valueConsistsOf: 'ALL',
            // define the default value
            value: null,
            // define options
            options: [],
            arr: [],













            //批量操作的数组
            selectedRows: [],




            //容器数据
            RouqiDiago: false,//容器弹框
            Rouqi: [],//容器数据
            RouqiTatol: 0,//最大页码
            RouqiPage: {//页码树
                page: 1,
                limit: 10,
                k: '',
                t: '',
            },
            //冻存架数据
            JiaDiago: false,//冻存架弹框
            Jia: [],//冻存架数据
            JiaTatol: 0,//最大页码
            JiaPage: {//页码树
                page: 1,
                limit: 10,
                k: '',
                t: '',
                equipmentId: 335,
            },

            //盒子数据
            HeDiago: false,//盒子弹框
            He: [],//盒子数据
            HeTatol: 0,//最大页码
            HePage: {//页码树
                page: 1,
                limit: 10,
                k: '',
                t: '',
            },

            rules: {
                code: [
                    { required: true, message: "任务编码不能为空", trigger: "blur" },
                ],
                name: [
                    { required: true, message: "任务名称不能为空", trigger: "blur" },
                ],
            },
            encodingType: [
                { label: "纯数字", value: "1" },
                { label: "混合", value: "2" },
            ],
        }
    },
    methods: {
        //容器的查询
        async geRouqiList() {
            this.RouqiPage.t = new Date().getTime()
            const { data: res } = await this.axios.get("api/biosample/equipment/list", {
                params: this.RouqiPage
            })
            // console.log(res);
            this.Rouqi = res.page.list;
            // console.log(this.assignmentList);
            this.RouqiTatol = res.page.totalCount;//最大页数
            if (res.code != 0) return this.$message.error("获取容器列表失败");
        },
        //容器的选择
        handleEditT(row) {
            // console.log(row);
            this.RRRROU.rouqi = row.name;
            this.addassignment.equipmentId = row.id;
            this.JiaPage.equipmentId = row.id;
            this.RouqiDiago = false;
        },
        //容器弹出框
        Rouclick() {
            this.RouqiDiago = true;
            this.geRouqiList();
        },
        //----------------------------------------------------------------------------------------------------------------
        //冻存架查询
        async geJiaList() {
            this.JiaPage.t = new Date().getTime()
            const { data: res } = await this.axios.get("api/biosample/forzenshelf/list", {
                params: this.JiaPage
            })
            this.Jia = res.page.list;
            this.JiaTatol = res.page.totalCount;
        },
        //架子的选择
        handleEditTJ(row) {
            // console.log(row);
            this.RRRROU.jia = row.code;
            this.addassignment.shelfId = row.id;
            this.addassignment.rowNo = row.rowNo;
            this.addassignment.columnNo = row.columnNo;
            this.JiaDiago = false;
        },
        //冻存架弹出框
        jiaclick() {
            this.JiaDiago = true;
            this.geJiaList();
        },
        //--------------------------------------------------------------------------------------------------------------
        //盒子查询
        async geHeList() {
            this.JiaPage.t = new Date().getTime()
            const { data: res } = await this.axios.get("api/biosample/forzenboxtype/list", {
                params: this.HePage
            })
            this.He = res.page.list;
            this.HeTatol = res.page.totalCount;
        },
        //盒子的选择
        handleEditTJH(row) {
            // console.log(row);
            this.RRRROU.he = row.name;
            this.addassignment.boxTypeId = row.id;
            this.addassignment.boxTypeName = row.name;
            this.addassignment.rowNums = row.rowNums;
            this.addassignment.columnNums = row.columnNums;
            this.HeDiago = false;
        },
        //盒子弹出框
        Heclick() {
            this.HeDiago = true;
            this.geHeList();
        },




        lookForm(){
            this.queryInfo= {
                t: '',
                page: 1,
                limit: 10,
                username: '',
            };
            this.getassignmentList();
        },






  //菜单添加
  async getRoleList() {
            let t = new Date().getTime();
            const { data: res } = await this.axios.get("api/sys/menu/list", t)
            const transformedData = res.map(item => ({
                title: item.name,
                id: item.menuId,
                parentId: item.parentId,
            }));
            this.arr = this.buildHierarchy(transformedData);
           
            this.options = this.arr
            // this.assignmentList = ARR;
                // console.log( JSON.stringify(ARR, null, 2));
            
        },
        buildHierarchy(items, idKey = 'id', parentIdKey = 'parentId') {
            // 创建一个空对象来存储所有项，以便快速查找  
            const itemLookup = {};
            // 创建一个空数组来存储最终的层级结构  
            const hierarchy = [];

            // 遍历所有项，将它们存储到itemLookup中  
            items.forEach(item => {
                itemLookup[item[idKey]] = { ...item, children: [] };
            });

            // 遍历所有项，构建层级结构  
            items.forEach(item => {
                const { [idKey]: menuId, [parentIdKey]: parentId } = item;
                // 如果parentId为空或未定义，表示这是顶级项  
                if (parentId === null || parentId === undefined || parentId === 0) {
                    hierarchy.push(itemLookup[menuId]);
                } else {
                    // 否则，将此项添加到其父级的children数组中  
                    if (itemLookup[parentId]) {
                        itemLookup[parentId].children.push(itemLookup[menuId]);
                    }
                }
            });

            return hierarchy;
        },
         // 字段默认 id label 用于规范化数据源
         tenantIdnormalizer(node) {
            if (node.children && !node.children.length) {
                delete node.children
            }
            return {
                id: node.id,
                label: node.title,
                children: node.children
            }
        },


        








        //获取列表数据
        async getRoleListA() {
            let t = new Date().getTime();
            const { data: res } = await this.axios.get("api/sys/menu/list", t)
            let ARR =  this.buildHierarchyA(res);
            // console.log( JSON.stringify(ARR, null, 2));
            this.assignmentList = ARR;
        },



        buildHierarchyA(items, idKey = 'menuId', parentIdKey = 'parentId') {
            // 创建一个空对象来存储所有项，以便快速查找  
            const itemLookup = {};
            // 创建一个空数组来存储最终的层级结构  
            const hierarchy = [];

            // 遍历所有项，将它们存储到itemLookup中  
            items.forEach(item => {
                itemLookup[item[idKey]] = { ...item, children: [] };
            });

            // 遍历所有项，构建层级结构  
            items.forEach(item => {
                const { [idKey]: menuId, [parentIdKey]: parentId } = item;
                // 如果parentId为空或未定义，表示这是顶级项  
                if (parentId === null || parentId === undefined || parentId === 0) {
                    hierarchy.push(itemLookup[menuId]);
                } else {
                    // 否则，将此项添加到其父级的children数组中  
                    if (itemLookup[parentId]) {
                        itemLookup[parentId].children.push(itemLookup[menuId]);
                    }
                }
            });

            return hierarchy;
        },












        






        //初始化数据
        addForms() {
            this.id = '';
            this.Type = 1;
            this.addassignment = {
                "t": 1729667138714,
                "type": 1,//类型
                "name": "",//菜单名称
                "parentId": '',//上级菜单的ID
                "url": "",//菜单路由
                "perms": "",//授权标识
                "orderNum": 1,//排序号
                "icon": "xiangqufill"//ICO
            };
            this.cataloguement={
                "t": 1729668942169,
                "type": 0,
                "name": "",
                "parentId": 1,
                "url": 0,
                "perms": 0,
                "orderNum": 1,
                "icon": "admin"
            };
            this.buttons={
                "t": 1729670921585,
                "type": 2,
                "name": "",
                "parentId": 210,
                "url": 0,
                "perms": "",
                "orderNum": 0,
                "icon": ""
            };

            this.passwordOK = '';
            this.dialogFormVisible = true;
            this.getRoleList();
        },
        // 获取任务列表
        async getassignmentList() {
            this.queryInfo.t = new Date().getTime()
            const { data: res } = await this.axios.get("api/sys/role/list", {
                params: this.queryInfo
            })
            // console.log(res);
            this.assignmentList = res.page.list;
            // console.log(this.assignmentList);
            this.total = res.page.totalCount;//最大页数
            if (res.code != 0) return this.$message.error("获取任务列表失败");
        },
        
        //添加新增-------------------------------------------------------------------------------------------------【菜单】
        async addForm() {
            this.addassignment.t = new Date().getTime();
            this.addassignment.type = this.Type;
            const { data: res } = await this.axios.post("api/sys/menu/save", this.addassignment);
            if (res.code != 0) return this.$message.error("新增失败");
            if(res.code== 500) return this.$message.error(res.msg);
            this.$message.success("新增成功");
            this.dialogFormVisible = false;
            this.getRoleList();
        },
        //---------------------------------------------------------------------------------------------------------【目录】
        async addFormA() {
            this.cataloguement.t = new Date().getTime();
            this.cataloguement.type = this.Type;
            const { data: res } = await this.axios.post("api/sys/menu/save", this.cataloguement);
            if (res.code != 0) return this.$message.error("新增失败");
            if(res.code== 500) return this.$message.error(res.msg);
            this.$message.success("新增成功");
            this.dialogFormVisible = false;
            this.getRoleList();
        },

        //---------------------------------------------------------------------------------------------------------【按钮】
        async addFormB() {
            this.buttons.t = new Date().getTime();
            this.buttons.type = this.Type;
            const { data: res } = await this.axios.post("api/sys/menu/save", this.buttons);
            if (res.code != 0) return this.$message.error("新增失败");
            if(res.code == 500) return this.$message.error(res.msg);
            this.$message.success("新增成功");
            this.dialogFormVisible = false;
            this.getRoleList();
        },





























        
        // 表格回显
        async handleEdit(row) {
            // console.log(row);
            this.getRoleList();
            this.Type = row.type;
            this.dialogFormVisible = true;
            this.id = row.menuId;
            this.addassignment.t = new Date().getTime();
            this.cataloguement.t = new Date().getTime();
            this.buttons.t = new Date().getTime();
            const { data: res } = await this.axios.get(`api/sys/menu/info/${this.id}`, this.addassignment.t);
            this.addassignment = res.menu;
            this.cataloguement = res.menu;
            this.buttons = res.menu;
        },
        //修改的接口---------------------------------------------------------------------------------------------------【菜单】
        async editForm() {
            this.addassignment.t = new Date().getTime();
            this.cataloguement.t = new Date().getTime();
            this.buttons.t = new Date().getTime();
            const { data: res } = await this.axios.post("api/sys/menu/update", this.addassignment);
            if (res.code != 0) return this.$message.error("修改失败");
            this.$message.success("修改成功");
            this.dialogFormVisible = false;
            this.getRoleList();
        },
          //修改的接口---------------------------------------------------------------------------------------------------【目录】
          async editFormA() {
            this.addassignment.t = new Date().getTime();
            this.cataloguement.t = new Date().getTime();
            this.buttons.t = new Date().getTime();
            const { data: res } = await this.axios.post("api/sys/menu/update", this.cataloguement);
            if (res.code != 0) return this.$message.error("修改失败");
            this.$message.success("修改成功");
            this.dialogFormVisible = false;
            this.getRoleList();
        },
          //修改的接口---------------------------------------------------------------------------------------------------【按钮】
          async editFormB() {
            this.addassignment.t = new Date().getTime();
            this.cataloguement.t = new Date().getTime();
            this.buttons.t = new Date().getTime();
            const { data: res } = await this.axios.post("api/sys/menu/update", this.buttons);
            if (res.code != 0) return this.$message.error("修改失败");
            this.$message.success("修改成功");
            this.dialogFormVisible = false;
            this.getRoleList();
        },

























        
        //单个删除
        handleDelete(row) {
            // console.log(row);
            this.$confirm(`是否删除[${row.menuId}]数据?`, "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(() => {
                    this.deleteTeam(row.menuId);
                })
                .catch(() => {
                    this.$message({
                        type: "info",
                        message: "已取消删除",
                    });
                });
        },
        async deleteTeam(id) {
            const { data: res } = await this.axios.post(`api/sys/menu/delete/${id}`);
            if (res.code != 0) return this.$message.error("删除失败");
            this.$message.success("删除成功");
            this.getRoleList();
        },
        // 分页器
        setRows(val) {
            this.queryInfo.limit = val;
            this.getassignmentList();
            this.RouqiPage.limit = val;
            this.geRouqiList();
            this.JiaPage.limit = val;
            this.geJiaList();
            this.HePage.limit = val;
            this.geHeList();
        },
        setPage(val) {
            this.queryInfo.page = val;
            this.getassignmentList();
            this.RouqiPage.page = val;
            this.geRouqiList();
            this.JiaPage.page = val;
            this.geJiaList();
            this.HePage.page = val;
            this.geHeList();
        },
        //批量删除
        handleSelectionChange(selection) {
            // this.selectedRows = selection;
            // console.log('Selected Rows:', this.selectedRows);
            this.selectedRows = selection.map(item => item.roleId);
            // console.log( this.selectedRows);
            if (this.selectedRows.length > 0) {
                this.esdisabled = false
            } else {
                this.esdisabled = true
            }

        },
        machDelete(id) {
            // console.log(row);
            this.$confirm(`是否删除[${id}]数据?`, "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(() => {
                    this.handledeleteTeam(id);
                })
                .catch(() => {
                    this.$message({
                        type: "info",
                        message: "已取消删除",
                    });
                });
        },
        async handledeleteTeam(id) {
            const { data: res } = await this.axios.post(`api/sys/role/delete`, id);
            if (res.code != 0) return this.$message.error("删除失败");
            this.$message.success("删除成功");
            this.getassignmentList();
        },
        //取消操作
        resetForm() {
            this.addForms();
            this.dialogFormVisible = false;
        },
        //加减框
        //层
        Age(val) {
            this.addassignment.orderNum = val;
        },
        //列
        column(val) {
            this.addassignment.columnNums = val;
        },
        //宽
        width(val) {
            this.cataloguement.orderNum = val;
        },
        //深
        depth(val) {
            this.addassignment.height = val;
        },
    },
    mounted() {
        this.getRoleListA()
    },
    components: {
        Pagination
    }
}
</script>

<style lang="scss" scoped>
::v-deep .el-table .cell {
    text-align: center;
}
::v-deep .vue-treeselect__menu{
    width: 300px !important;
}
main {

    padding: 20px;
    background-color: #fff;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);
}

.el-header {
    padding: 0;
    float: left;
    width: 100%;
    ;

    .el-input {
        width: 185px;
        margin-right: 15px;
    }

    .delet {
        color: #fff;
        background-color: #fab6b6;
        border-color: #fab6b6;
    }

    .active {
        color: #fff;
        background-color: #f56c6c;
        border-color: #f56c6c;
    }

    .add {
        color: #fff;
        background-color: #17b3a3;
        border-color: #17b3a3;
    }
}
</style>